package cn.edu.ctbu.labtest.webapi;

import cn.edu.ctbu.labtest.domain.Student;
import cn.edu.ctbu.labtest.domain.Teacher;
import cn.edu.ctbu.labtest.service.StudentService;
import cn.edu.ctbu.labtest.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/webapi/login")
public class LoginRestController {

    @Autowired
    StudentService studentService;
    @Autowired
    TeacherService teacherService;

    /**
     * 读取的url:"/webapi/login/user"
     * @param httprequest
     * @param username
     * @param password
     * @param radioVal
     * @return
     */
    @GetMapping("/user")
    public int user(HttpServletRequest httprequest,String username,String password,Integer radioVal) {
        //判断用户名和密码是否存在

        if (radioVal == 1) {//学生登录
            List<Student> students = studentService.findByNameAndPassword(username, password);
            if (students.size() > 0) {
                //如果存在用户名和密码，写入session
                HttpSession session = httprequest.getSession();
                session.setAttribute("userid", students.get(0).getId());
                session.setAttribute("user", students.get(0));
                return 1; //成功
            } else {
                //如果不存在返回出错
                //登录用户不存在
                return -1;
            }
        }
        else if (radioVal == 2) {//教师登录
            List<Teacher> teachers = teacherService.findByNameAndPassword(username, password);
            if (teachers.size() > 0) {
                HttpSession session = httprequest.getSession();
                session.setAttribute("userid", teachers.get(0).getId());
                session.setAttribute("user", teachers.get(0));
                return 2;//成功
            } else {
                //如果不存在返回出错
                //登录用户不存在
                return -1;
            }
        }
        else{//未选择登录用户类型
            return -2;
        }
    }


//    /**
//     *读取的url:/webapi/student/self
//     */
//    @GetMapping("/self")
//    public int self(HttpServletRequest httprequest,String username,String password,Integer radioVal)
//    {
//        if (radioVal == 1){
//            List<Student> students = studentService.findByNameAndPassword(username, password);
//        }
//
//    }
//
}
